package com.lottery.game.core.modules.service.app;

import com.lottery.game.core.modules.entity.user.WebsocketMessage;
import com.lottery.game.core.modules.mapper.WebsocketMessageDao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

@Service
public class WebsocketMessageService {

	@Autowired
	private WebsocketMessageDao websocketMessageDao;

	public void saveWebsocketMessage(String senderNickname,
			String sendMsg,
			String userId,
			String roomNumber,
			String chatType,
			Integer gameStatus,
			Integer messageStatus) {
		WebsocketMessage message = new WebsocketMessage();
		message.setSenderNickname(senderNickname);
		message.setSendMsg(sendMsg);
		message.setUserId(userId);
		message.setRoomNumber(roomNumber);
		message.setChatType(chatType);
		message.setGameStatus(gameStatus);
		message.setMessageStatus(messageStatus);

		String id = UUID.randomUUID().toString().replace("-","");
		message.setId(id);
		message.setId(id);

		message.setCreateTime(currentDate());
		websocketMessageDao.insert(message);
	}
	
	public WebsocketMessage saveWebsocketMessage2(String senderNickname,
			String sendMsg,
			String userId,
			String roomNumber,
			String chatType,
			Integer gameStatus,
			Integer messageStatus) {
		WebsocketMessage message = new WebsocketMessage();
		message.setSenderNickname(senderNickname);
		message.setSendMsg(sendMsg);
		message.setUserId(userId);
		message.setRoomNumber(roomNumber);
		message.setChatType(chatType);
		message.setGameStatus(gameStatus);
		message.setMessageStatus(messageStatus);

		String id = UUID.randomUUID().toString().replace("-","");
		message.setId(id);
		message.setId(id);

		message.setCreateTime(currentDate());
		if(websocketMessageDao.insert(message)>0) {
			return message;
		}
		return null;
	}

	public void updateWebsocketMessageStatus(String messageId) {
		websocketMessageDao.updateReceiveStatus(messageId, currentDate());
	}

	public List<WebsocketMessage> findUnreceivedMessages() {
		return websocketMessageDao.getUnreceivedMessageList();
	}

	private String currentDate() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));

		return sdf.format(date);
	}

}
